package cn.jtfadmin.base.shiro.support;

import cn.jtfadmin.base.lang.common.security.UserDetails;
import cn.jtfadmin.base.shiro.config.ShiroAutoConfiguration;
import cn.jtfadmin.base.shiro.config.UserBuilder;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.util.CollectionUtils;

import java.util.*;


/**
 * noRealm, 当没有配置reaml时使用
 *
 * @author jtf
 * @see ShiroAutoConfiguration#defaultRealm(List)
 *  @since 0.0.1
 */
public class DefaultRealm extends AuthorizingRealm {


    private List<UserBuilder> userBuilders ;

    public DefaultRealm(List<UserBuilder> userBuilders){
        setCredentialsMatcher(ShiroPasswordMatch.getShiroCredentialMatch());
        this.userBuilders = userBuilders;
    }


    @Override
    public boolean supports(AuthenticationToken token) {
        return true;
    }



    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        Object principal = token.getPrincipal();
        if (Objects.isNull(principal)) {
            throw new UnknownAccountException("账户不能为空");
        }
        UserDetails userDetails = PrincipalUtils.buildUserDetails( token);
        if(Objects.isNull(userDetails)){
            throw new UnknownAccountException("账户不存在");
        }
        SimpleAccount simpleAccount = new SimpleAccount(
                PrincipalUtils.createPrincipalCollection(userDetails,getName()),
                userDetails.getPassword());
        Set<String> allPermission = userDetails.allPermissions();
        if (!CollectionUtils.isEmpty(allPermission)) {
            simpleAccount.setStringPermissions(allPermission);
        }
        simpleAccount.setRoles(userDetails.allUserType());
        return simpleAccount;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        Collection collection = principals.fromRealm(getName());
        Iterator iterator = collection.iterator();
        while (iterator.hasNext()){
            Object next = iterator.next();
            if(next instanceof UserDetails){
                SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
                UserDetails userDetails = (UserDetails) next;
                Set<String> allPermission = userDetails.allPermissions();
                if (!CollectionUtils.isEmpty(allPermission)) {
                    simpleAuthorizationInfo.setStringPermissions(allPermission);
                }
                simpleAuthorizationInfo.setRoles(userDetails.allUserType());
                return simpleAuthorizationInfo;
            }
        }
        return null;
    }
}
